package cn.msn.user.service.impl;

import cn.msn.basic.exception.BusinessException;
import cn.msn.basic.jwt.JwtUtils;
import cn.msn.basic.jwt.LoginData;
import cn.msn.basic.jwt.RsaUtils;
import cn.msn.basic.service.impl.BaseServiceImpl;
import cn.msn.basic.util.AjaxResult;
import cn.msn.basic.util.HttpUtil;
import cn.msn.basic.util.Md5Utils;
import cn.msn.basic.util.StrUtils;
import cn.msn.system.domain.Menu;
import cn.msn.system.mapper.MenuMapper;
import cn.msn.system.mapper.PermissionMapper;
import cn.msn.user.constant.WxConstants;
import cn.msn.user.domain.Logininfo;
import cn.msn.user.domain.User;
import cn.msn.user.domain.Wxuser;
import cn.msn.user.dto.LoginDto;
import cn.msn.user.mapper.LogininfoMapper;
import cn.msn.user.mapper.UserMapper;
import cn.msn.user.mapper.WxuserMapper;
import cn.msn.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        // 1.通过account和type查数据库
        Logininfo logininfo= logininfoMapper.accountLogin(loginDto);
        // 2.判断
        if (logininfo == null) {
            throw new BusinessException("用户名错误");
        } else {
            // 3.判断密码
            String inputPwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if (!inputPwd.equals(logininfo.getPassword())) {
                throw new BusinessException("密码错误");
            } else {
              /*  // 成功登录
                String token = UUID.randomUUID().toString();
                // 保存到redis实现序列化
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                // 4.将token、登陆对象存到MAP
                Map<String, Object> map = new HashMap<>();
                map.put("token",token);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                return map;
              */
                // 登录成功，JWT操作
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return map;
            }
        }
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("logininfo",logininfo);
        // 封装为LoginData对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        if (logininfo.getType()==0){
            // 1.后台管理员，获取当前登录人所有菜单
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId());
            // 1.后台管理员，获取当前登录人所有权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
            map.put("menus",menus);
            map.put("permissions",permissions);
        }
        try {
            // 3. 获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            // 4.通过私钥对LoginData加密成Jwt字符串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            // 5. 将以上信息封装到Map，返回给前端
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map  ;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        // 1.准备请求和替换参数
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE",code);
        // 2.使用HttpUtil发送请求
        String jsonStr = HttpUtil.httpGet(url);
        // 3.对返回的json字符串做处理
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 4.根据opndid去查t_wxuser对象
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        // 4.1.如果有 = 绑定了 = return true给前端，做免密登录
        if (wxuser!=null && wxuser.getUserId()!=null) {
            User user = userMapper.loadById(wxuser.getUserId());
            if (user!=null) {
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                // 登录成功，JWT操作
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        String params = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        // 1.校验空值 -手机号码和手机验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空！");
        }
        // 2.校验手机验证码是否过期，是否正确
        Object codeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if (codeObj == null) {
            throw new BusinessException("验证码已过期，请重新获取！");
        }
        if (!codeObj.toString().split(":")[0].equals(verifyCode)) {
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 3.获取wxuser对象 -发送请求 -json字符串
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        // 4.通过phone查询user
        User user = userMapper.loadByPhone(phone);
        // 5.如果为空，根据phone创建user对象 -创建logininfo对象 -保存logininfo对象 -再保存user对象
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        // 6.有user对象，直接将user对象的id设置到wxuser中
        wxuser.setUserId(user.getId());
        // 7.将wxuser对象添加到数据库
        wxuserMapper.save(wxuser);
        // 8.免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        // 登录成功，JWT操作
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(result);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country")
                + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl("headimgurl");
        wxuser.setUnionid("unionid");
        return wxuser;
    }
}

